<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use function EasyWeChat\Kernel\Support\get_client_ip;
use EasyWeChatComposer\EasyWeChatComposer\EasyWeChat;
use Omnipay\Omnipay;
use Illuminate\Http\Request;
use Session;
use App\Services\OrderService;
use App\Models\MemberActivityModel;

class WechatController extends Controller{
    public function pay(){
        $order_id = $_POST['order_id'] ? intval($_POST['order_id']) : 1;
        $openid = $_POST['openid'] ? addslashes($_POST['openid']) : '';
        $code = $_POST['code'] ? addslashes($_POST['code']) : '';
//        $access_token = $_POST['access_token'] ? addslashes($_POST['access_token']) : '';

        if($openid == ''){
            $_data = array('code'=>'3x000002','msg'=>'请传入openid');
            return response()->json($_data);
        }

        if($code == ''){
            $_data = array('code'=>'3x000003','msg'=>'请传入code');
            return response()->json($_data);
        }

        $order = new OrderService;
        $orderInfo = $order->getOrderInfo($order_id);


        if(strpos($orderInfo['ordernum'],'Realia') !== False){
            $body = '【爆炸狗教具】订单支付';
        }

        if(strpos($orderInfo['ordernum'],'Course') !== False){
            $body = '【爆炸狗课程】订单支付';
        }

        if(strpos($orderInfo['ordernum'],'Realias') !== False){
            $body = '【爆炸狗教具包】订单支付';
        }

        if(strpos($orderInfo['ordernum'],'Activity') !== false){
            $body = '【爆炸狗活动】订单支付';
        }

        $getway = $this->gateway();
        $order = array(
            'body'              => $body,
            'out_trade_no'      => $orderInfo['ordernum'],
            'total_fee'         => intval($orderInfo['payment'])*100, //=0.01
            'spbill_create_ip'  => get_client_ip(),
            'notify_url'        => 'http://admin.boomdog.cn/wechat/notify',
            'fee_type'          => 'CNY',
            'openid'            => $openid,
        );

        $request  = $getway->purchase($order);
        $response = $request->send();
        if(!$response->isSuccessful()){
            $ret = $response->getData();
            throw new \Exception('支付失败');
        }

        $arr = $response->getJsOrderData();
        $_data = array('code'=>'2x000001','msg'=>'ok','data'=>array('code'=>$code,'data'=>$arr));

        return response()->json($_data);
    }

    public function notify(){
        $order =  new OrderService;
        $getway = $this->gateway();

        $request = $getway->completePurchase([
            'request_params' => file_get_contents('php://input')
        ])->send();

        if($request->isPaid()){
            $payData = $request->getRequestData();
            info($payData);
            $out_trade_no = $payData['out_trade_no'];
            $orderInfo = $order->getOrderInfoBySn($out_trade_no);
            if($orderInfo['pay_status'] == 40) return;
            date_default_timezone_set('PRC');
            $action_data['order_id'] = $orderInfo['id'];
            $action_data['ordernum'] = $orderInfo['ordernum'];
            $action_data['logtime'] = date('Y-m-d');

            $data['pay_status'] = 40;
            if($orderInfo['product_type'] == 1 || $orderInfo['product_type'] == 4){
                $data['composition_status'] = 50;
            }else{
                $data['composition_status'] = 30;
            }
            $data['payment_time'] = date('Y-m-d H:i:s');
            $data['update_date'] = date('Y-m-d H:i:s');

            $res = $order->updateOrder($orderInfo['id'],$data);
            $action_data['pay_status'] = 40;
            if($res){
                $action_data['action_note'] = '微信支付成功，更改订单状态成功';
            }else{
                $action_data['action_note'] = '微信支付成功，更改订单状态失败';
            }

            $order->insertOrderLog($action_data);

            exit("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
        }
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
//    public function xml2Array($xml) {
//        //禁止引用外部xml实体
//        libxml_disable_entity_loader(true);
//        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
//        return $result;
//    }

    private function gateway(){
        $getway = Omnipay::create('WechatPay_Js');
        $getway->setAppId('wx8bce72636ba79f5e');
        $getway->setMchId('1584531831');
        $getway->setApiKey('5e9d5a389d904MRGMWFpfQWjpkRK1oQF');

        return $getway;
    }

}
